# coding:utf-8
from __future__ import absolute_import
from src import const
from src.osm import Xapi
import argparse
import os
import logging
import sys
from .download_xml import main
import time
import traceback
from src.errors import XapiQuotaException

download_dict = [
    # ('landuse', 'residential'),
    # ('landuse', 'forest'),
    # ('landuse', 'farm'),
    # ('landuse', 'commercial'),

    # ('natural', 'water', 'china_jzh'),
    # ('natural', 'wood', 'china_jzh'),

    # ('building', 'house', 'china_east'),
    # ('building', 'residential', 'china_east'),
    # ('building', 'industrial'),
    # ('building', 'commercial'),
    ('building', 'school'),
    # ('building', 'retail'),

]

download_dict.reverse()


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--save-path', default='data/china/')
    parser.add_argument('-r', '--default-region', default='china')
    return parser.parse_args()


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    args = parse_args()
    i = 0
    while i < len(download_dict):
        item = download_dict[i]
        logging.info('Download %s => %s......' % (item[0], item[1]))
        args.tag_keyword = item[0]
        args.tag_value = item[1]
        if len(item) > 2:
            args.region = item[2]
            logging.warning('Use region: ' + item[2])
        else:
            args.region = args.default_region
        try:
            main(args)
            i += 1
        except XapiQuotaException:
            logging.warning('Xapi Quota Exception. Wait 5 minutes.')
            time.sleep(300)
        except Exception:
            logging.error(traceback.format_exc())
